package com.czr.service.archives;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.czr.entity.Blog;
import com.czr.mapper.BlogMapper;
import com.czr.service.blog.BlogService;
import com.czr.vo.ArticleWithYearVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Description:
 * Author: czr czr
 * Version: 1.0
 * Create Date Time: 2021/11/27 21:45.
 * Update Date Time:
 *
 * @see
 */
@Service
@Slf4j
public class ArchivesServiceImpl implements ArchivesService {

    @Autowired
    private BlogService blogService;

    @Autowired
    private BlogMapper blogMapper;

    @Override
    public List<ArticleWithYearVo> queryBlogYearGroup() {

        List<Integer> years = blogMapper.queryBlogYearGroup();
        return years.stream().map(year -> {
            ArticleWithYearVo awyv = new ArticleWithYearVo();
            // 1、年份
            awyv.setYear(year);
            // 2、根据年份查询分页对应的文章
            IPage<Blog> blogIPage = this.findblogPages(year, 1, 6);
            if (!CollectionUtils.isEmpty(blogIPage.getRecords())) {
                List<Map<String, Object>> collect = blogIPage.getRecords().stream().map(blog -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("id", blog.getId());
                    map.put("title", blog.getTitle());
                    map.put("createTime", blog.getCreateTime());
                    return map;
                }).collect(Collectors.toList());
                awyv.setArticlesList(collect);
            } else {
                awyv.setArticlesList(new ArrayList<>()); // 注意：这里为什么要放进去，原因补齐数据格式 []
            }
            // 3: 把查询分页的信息放入到pageMap中
            Map<String, Object> pageMap = new HashMap<>();
            pageMap.put("total" ,blogIPage.getTotal());
            pageMap.put("pages" ,blogIPage.getPages());
            pageMap.put("pageNo" ,blogIPage.getCurrent());
            pageMap.put("pageSize" ,blogIPage.getSize());
            awyv.setPageMap(pageMap);
            return awyv;
        }).sorted((b,a) -> a.getYear() - b.getYear()).collect(Collectors.toList());

    }

    public IPage<Blog> findblogPages(Integer year, Integer pageNo, Integer pageSize) {
        //1 : 设置分页
        Page<Blog> page = new Page<>(pageNo, pageSize);
        //2：设置查询条件
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("id,title,create_time");
        queryWrapper.eq("DATE_FORMAT(create_time,'%Y')", year);
        queryWrapper.eq("status", 1);
        queryWrapper.eq("is_delete", 0);
        queryWrapper.orderByDesc("create_time");
        // 3:查询分页返回
        return blogMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<Map<String, Object>> queryBlogPages(Integer year, Integer pageNo, Integer pageSize) {
        List<Blog> blogs = this.findblogPages(year, pageNo, pageSize).getRecords();
        return blogs.stream().map(blog -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", blog.getId());
            map.put("title", blog.getTitle());
            map.put("createTime", blog.getCreateTime());
            return map;
        }).collect(Collectors.toList());

    }


    @Override
    public List<HashMap<String, Object>> findBlogYearGroup() {
        // 查询所有年份
        List<String> blogYearGroup = blogMapper.findBlogYearGroup();
        // 根据年份查询对应的年份文章进行分页
        List<HashMap<String, Object>> collect = blogYearGroup.stream().map(year -> {

            HashMap<String, Object> map = new HashMap<>();
            // 根据年份查询对应的每个年份的前10条数据
            IPage<Blog> ipageList = findChildrenBlogByYear(Integer.parseInt(year), 1, 10);
            map.put("year", year);
            map.put("current", ipageList.getCurrent());
            map.put("pages", ipageList.getPages());
            map.put("total", ipageList.getTotal());
            map.put("pageSize", ipageList.getSize());
            map.put("blogList", CollectionUtils.isEmpty(ipageList.getRecords()) ? new ArrayList<>() : ipageList.getRecords());
            return map;
        }).collect(Collectors.toList());

        return collect;
    }
    
    public IPage<Blog> findChildrenBlogByYear(Integer year, int pageNo, int pageSize) {
        // 创建分页
        Page<Blog> blogIPage = new Page<>(pageNo, pageSize);
        // 设定查询条件
        QueryWrapper<Blog> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("DATE_FORMAT(kb.create_time,'%Y')", year);
        queryWrapper.eq("kb.status", 1);
        queryWrapper.eq("kb.is_delete", 0);
        queryWrapper.orderByDesc("kb.create_time");

        IPage<Blog> childrenBlogByYear = blogMapper.findChildrenBlogByYear(blogIPage, queryWrapper);

        return childrenBlogByYear;
    }


    @Override
    public List<HashMap<String, Object>> getAllArchives() {

        LambdaQueryWrapper<Blog> queryWrapper = new LambdaQueryWrapper<>();
        // 只查询发布的数据
        queryWrapper.eq(Blog::getStatus, 1);
        // 排除指定列
        queryWrapper.select(Blog.class, s -> !s.getColumn().equals("content") && !s.getColumn().equals("status"));

        List<Blog> bloglist = blogService.list(queryWrapper);

        Map<Integer, List<Blog>> collect =bloglist.stream().collect(Collectors.groupingBy(blog -> blog.getCreateTime().getYear()));

        List<HashMap<String, Object>> collect1 = collect.entrySet().stream().map(entry -> {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("year", entry.getKey());
            hashMap.put("articlesList", entry.getValue());
            return hashMap;
        }).sorted((o2,o1) -> (int)o1.get("year") - (int)o2.get("year")).collect(Collectors.toList());

        return collect1;
    }

    /*public Map<Integer, List<Blog>> sortTreeMap(Map<Integer, List<Blog>> collect2) {
        // 因为这个底层是hashMap乱序的 定义一个treeMap
        // treeMap确实有排序的功能，就是它的排序必须在初始化的时候确认，否则无效
        TreeMap<Integer, List<Blog>> newCollect = new TreeMap<>((o2,o1) -> o1-o2);
        *//*TreeMap<Integer, List<Blog>> collect =collect2.stream()
                .collect(Collectors.groupingBy(blog -> blog.getCreateTime().getYear(), TreeMap::new, Collectors.toList()));*//*

        collect2.forEach((k,v) -> {
            newCollect.put(k,v);
        });
        return newCollect;
    }*/

    @Override
    // 使用List方式返回
    public List<ArticleWithYearVo> getAllArchives2() {

        LambdaQueryWrapper<Blog> queryWrapper = new LambdaQueryWrapper<>();
        // 只查询发布的数据
        queryWrapper.eq(Blog::getStatus, 1);
        // 排除指定列
        queryWrapper.select(Blog.class, s -> !s.getColumn().equals("content") && !s.getColumn().equals("status"));

        List<Blog> bloglist = blogService.list(queryWrapper);

        Map<Integer, List<Blog>> collect = bloglist.stream().collect(Collectors.groupingBy(blog -> blog.getCreateTime().getYear()));

        return collect.entrySet().stream().map(entry -> {

            ArticleWithYearVo articleWithYear = new ArticleWithYearVo();
            articleWithYear.setYear(entry.getKey());
            List<Map<String, Object>> collect1 = entry.getValue().stream().map(blog -> {
                HashMap<String, Object> blogHashMap = new HashMap<>();
                blogHashMap.put("id", blog.getId());
                blogHashMap.put("title", blog.getTitle());
                blogHashMap.put("createTime", blog.getCreateTime());
                return blogHashMap;
            }).collect(Collectors.toList());
            articleWithYear.setArticlesList(collect1);
            return articleWithYear;
        }).sorted((b, a) -> a.getYear() - b.getYear()).collect(Collectors.toList());
        //return collect2;
    }


}
